package com.wephone.Student.ui;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.format.Time;
import android.view.View;
import android.view.animation.AnticipateOvershootInterpolator;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.easemob.exceptions.EaseMobException;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.bean.StatusCode;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;
import com.umeng.socialize.media.UMImage;
import com.wephone.Student.BaseApplication;
import com.wephone.Student.R;
import com.wephone.Student.bean.BaseResponse;
import com.wephone.Student.bean.RegisterResponse;
import com.wephone.Student.bean.SearchCollegeResponse;
import com.wephone.Student.bean.data.CityData;
import com.wephone.Student.bean.data.CountryData;
import com.wephone.Student.bean.data.MyLocationInfo2;
import com.wephone.Student.bean.data.ProvinceData;
import com.wephone.Student.bean.data.SearchCollegeData;
import com.wephone.Student.huanxin.Constant;
import com.wephone.Student.huanxin.domain.User;
import com.wephone.Student.network.HttpClient;
import com.wephone.Student.network.MyResponseHandler;
import com.wephone.Student.util.Constants;
import com.wephone.Student.util.MD5;
import com.wephone.Student.util.ShareReferenceUtil;
import com.wephone.Student.wheel.widget.OnWheelChangedListener;
import com.wephone.Student.wheel.widget.StringWheelAdapter;
import com.wephone.Student.wheel.widget.WheelView;

public class MyLocationInfo2Activity extends BaseActivity {
	private TextView inputEdit1;
	private TextView inputEdit2;
	private AutoCompleteTextView inputEdit3;
	private AutoCompleteTextView inputEdit4;
	private TextView inputEdit5;
	private TextView inputEdit6;
	private int countryIdx;
	private int provinceIdx;
	private int cityIdx;
	private int homeIdx1;
	private int homeIdx2;
	private int locIdx1;
	private int locIdx2;
	private List<SearchCollegeData> searchCollegeList = new ArrayList<SearchCollegeData>();
	private long searchTime;
	private List<SearchCollegeData> searchCollegeList2 = new ArrayList<SearchCollegeData>();
	private long searchTime2;
	
	private String uPlatform;
	private String uPlatformid;
	private String gender;
	private String username;
	private String password;
	private String nick;
	private int _year;
	private int _month;
	private int _day;
	private String signature;
	private String photoSavedPath = null;
	public static int uLocType = -1;
	public static String uLocDetail = "";
	private ProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_my_location_info_2);
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			uPlatform = bundle.getString("uPlatform");
			uPlatformid = bundle.getString("uPlatformid");
			gender = bundle.getString("gender");
			username = bundle.getString("username");
			password = bundle.getString("password");
			nick = bundle.getString("nick");
			signature = bundle.getString("signature");
			_year = bundle.getInt("year");
			_month = bundle.getInt("month");
			_day = bundle.getInt("day");
			photoSavedPath = bundle.getString("photoSavedPath");
		}
		init();
	}
	
	AsyncHttpResponseHandler collegeHandler = new AsyncHttpResponseHandler(){
		@Override
		public void onFailure(Throwable arg0, String result) {
		}

		@Override
		public void onSuccess(String result) {
			if(!TextUtils.isEmpty(result)){
				try{
					Gson gson = new Gson();
					SearchCollegeResponse response = (SearchCollegeResponse)gson.fromJson(result, SearchCollegeResponse.class);
//					System.out.println("---message---"+response.getErrorMsg());
					if(response.getErrNo()!=null && response.getErrNo().equals("0")){
						if(response.getData()!=null && response.getData().size()>0){
							searchCollegeList.clear();
							searchCollegeList.addAll(response.getData());
							
							List<String> collegeNameArray = new ArrayList<String>();
							for(SearchCollegeData scd:searchCollegeList){
								collegeNameArray.add(scd.getName());
							}
							ArrayAdapter<String> av = new ArrayAdapter<String>(MyLocationInfo2Activity.this,R.layout.include_college_dropdown_item, collegeNameArray);
							inputEdit3.setAdapter(av);
//							inputEdit3.showDropDown();
						}
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	};
	
	AsyncHttpResponseHandler collegeHandler2 = new AsyncHttpResponseHandler(){
		@Override
		public void onFailure(Throwable arg0, String result) {
		}

		@Override
		public void onSuccess(String result) {
			if(!TextUtils.isEmpty(result)){
				try{
					Gson gson = new Gson();
					SearchCollegeResponse response = (SearchCollegeResponse)gson.fromJson(result, SearchCollegeResponse.class);
//					System.out.println("---message---"+response.getErrorMsg());
					if(response.getErrNo()!=null && response.getErrNo().equals("0")){
						if(response.getData()!=null && response.getData().size()>0){
							searchCollegeList2.clear();
							searchCollegeList2.addAll(response.getData());
							
							List<String> collegeNameArray = new ArrayList<String>();
							for(SearchCollegeData scd:searchCollegeList2){
								collegeNameArray.add(scd.getName());
							}
							ArrayAdapter<String> av = new ArrayAdapter<String>(MyLocationInfo2Activity.this,R.layout.include_college_dropdown_item, collegeNameArray);
							inputEdit4.setAdapter(av);
							inputEdit4.showDropDown();
						}
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	};
	
	private void init(){
		inputEdit1 = (TextView)findViewById(R.id.input_edit_1);
		inputEdit2 = (TextView)findViewById(R.id.input_edit_2);
		inputEdit3 = (AutoCompleteTextView)findViewById(R.id.input_edit_3);
		inputEdit4 = (AutoCompleteTextView)findViewById(R.id.input_edit_4);
		inputEdit5 = (TextView)findViewById(R.id.input_edit_5);
		inputEdit6 = (TextView)findViewById(R.id.input_edit_6);
		
		inputEdit3.addTextChangedListener(new TextWatcher(){
			@Override
			public void afterTextChanged(Editable arg0) {
				long nowTime = System.currentTimeMillis();
				if(nowTime - searchTime > 100){
					searchTime = nowTime;
					RequestParams params = new RequestParams();
					params.put("name", inputEdit3.getText().toString());
					if(!TextUtils.isEmpty(inputEdit1.getText().toString())){
						params.put("countryname", inputEdit1.getText().toString());
					}
					HttpClient.getInstance().get2(Constants.API_SEARCH_COLLEGE_URL, params, collegeHandler);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
			}

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
			}});
		
		inputEdit4.addTextChangedListener(new TextWatcher(){
			@Override
			public void afterTextChanged(Editable arg0) {
				long nowTime = System.currentTimeMillis();
				if(nowTime - searchTime2 > 100){
					searchTime2 = nowTime;
					RequestParams params = new RequestParams();
					params.put("name", inputEdit4.getText().toString());
					if(!TextUtils.isEmpty(inputEdit1.getText().toString())){
						params.put("countryname", inputEdit1.getText().toString());
					}
					HttpClient.getInstance().get2(Constants.API_SEARCH_COLLEGE_URL, params, collegeHandler2);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
			}

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
			}});
		
		inputEdit1.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				showChooseCountryDialog(getString(R.string.my_location_info_2_input_1));
			}
		});
		inputEdit2.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(TextUtils.isEmpty(inputEdit1.getText().toString())){
					Toast.makeText(getApplicationContext(), "请先选择曾经山楂的国家", Toast.LENGTH_SHORT).show();
				}else{
					showChooseCountryDialog2(getString(R.string.my_location_info_2_input_2));
				}
			}
		});
		inputEdit5.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				showChooseCountryDialog3(getString(R.string.my_location_info_2_input_5));
			}
		});
		
		inputEdit6.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				showChooseCountryDialog4(getString(R.string.my_location_info_2_input_6));
			}
		});
		
		findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		findViewById(R.id.btn_finish).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(TextUtils.isEmpty(inputEdit1.getText().toString())){
					Toast.makeText(getApplicationContext(), "曾经山楂的国家必须填写", Toast.LENGTH_SHORT).show();
					return;
				}else if(TextUtils.isEmpty(inputEdit2.getText().toString())){
					Toast.makeText(getApplicationContext(), "山楂的城市必须填写", Toast.LENGTH_SHORT).show();
					return;
				}else if(TextUtils.isEmpty(inputEdit3.getText().toString())){
					Toast.makeText(getApplicationContext(), "山楂的学校1必须填写", Toast.LENGTH_SHORT).show();
					return;
//				}else if(TextUtils.isEmpty(inputEdit4.getText().toString())){
//					Toast.makeText(getApplicationContext(), "山楂的学校2必须填写", Toast.LENGTH_SHORT).show();
//					return;
				}else if(TextUtils.isEmpty(inputEdit5.getText().toString())){
					Toast.makeText(getApplicationContext(), "家乡必须填写", Toast.LENGTH_SHORT).show();
					return;
				}else if(TextUtils.isEmpty(inputEdit6.getText().toString())){
					Toast.makeText(getApplicationContext(), "目前所在地必须填写", Toast.LENGTH_SHORT).show();
					return;
				}else{
					boolean hasFound1 = false;
					boolean hasFound2 = false;
					for(SearchCollegeData scd:searchCollegeList){
						if(scd.getName().equals(inputEdit3.getText().toString())){
							hasFound1 = true;
							break;
						}
					}
					if(!TextUtils.isEmpty(inputEdit4.getText().toString())){
						for(SearchCollegeData scd:searchCollegeList2){
							if(scd.getName().equals(inputEdit4.getText().toString())){
								hasFound2 = true;
								break;
							}
						}
					}else{
						hasFound2 = true;
					}
					if(!hasFound1){
						String msg = "没有找到匹配的学校！确定使用“"+inputEdit3.getText().toString()+"”吗？";
						if(!hasFound2){
							msg = "没有找到匹配的学校！确定使用“"+inputEdit3.getText().toString()+"”和“"+inputEdit4.getText().toString()+"”吗？";
						}
						new AlertDialog.Builder(MyLocationInfo2Activity.this)
						.setTitle("提示")
						.setMessage(msg)
						.setNegativeButton("取消", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
							}
						})
						.setPositiveButton("确定", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int whichButton) {
								registerNow();
							}
						}).show();
					}else{
						if(!hasFound2){
							new AlertDialog.Builder(MyLocationInfo2Activity.this)
							.setTitle("提示")
							.setMessage("没有找到匹配的学校！确定使用“"+inputEdit4.getText().toString()+"”吗？")
							.setNegativeButton("取消", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
								}
							})
							.setPositiveButton("确定", new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int whichButton) {
									registerNow();
								}
							}).show();
						}else{
							registerNow();
						}
					}
				}
			}
		});
		
		if(RegisterActivity.uLocType == 1 && !TextUtils.isEmpty(RegisterActivity.uLocDetail)){
			Gson gson = new Gson();
			MyLocationInfo2 info = gson.fromJson(RegisterActivity.uLocDetail, MyLocationInfo2.class);
			inputEdit1.setText(info.getCountry());
			inputEdit2.setText(info.getCity());
			inputEdit3.setText(info.getSchool1());
			inputEdit4.setText(info.getSchool2());
			inputEdit5.setText(info.getHome());
			inputEdit6.setText(info.getLoc());
			countryIdx = info.getCountryIdx();
			provinceIdx = info.getProvinceIdx();
			cityIdx = info.getCityIdx();
			homeIdx1 = info.getHomeIdx1();
			homeIdx2 = info.getHomeIdx2();
			locIdx1 = info.getLocIdx1();
			locIdx2 = info.getLocIdx2();
			
			if(!TextUtils.isEmpty(inputEdit3.getText().toString())){
				RequestParams params = new RequestParams();
				params.put("name", inputEdit3.getText().toString());
				if(!TextUtils.isEmpty(inputEdit1.getText().toString())){
					params.put("countryname", inputEdit1.getText().toString());
				}
				HttpClient.getInstance().get2(Constants.API_SEARCH_COLLEGE_URL, params, collegeHandler);
			}
			if(!TextUtils.isEmpty(inputEdit4.getText().toString())){
				RequestParams params = new RequestParams();
				params.put("name", inputEdit4.getText().toString());
				if(!TextUtils.isEmpty(inputEdit1.getText().toString())){
					params.put("countryname", inputEdit1.getText().toString());
				}
				HttpClient.getInstance().get2(Constants.API_SEARCH_COLLEGE_URL, params, collegeHandler2);
			}
		}else if(EditMyInfoActivity.uLocType == 1 && !TextUtils.isEmpty(EditMyInfoActivity.uLocDetail)){
			Gson gson = new Gson();
			MyLocationInfo2 info = gson.fromJson(EditMyInfoActivity.uLocDetail, MyLocationInfo2.class);
			inputEdit1.setText(info.getCountry());
			inputEdit2.setText(info.getCity());
			inputEdit3.setText(info.getSchool1());
			inputEdit4.setText(info.getSchool2());
			inputEdit5.setText(info.getHome());
			inputEdit6.setText(info.getLoc());
			countryIdx = info.getCountryIdx();
			provinceIdx = info.getProvinceIdx();
			cityIdx = info.getCityIdx();
			homeIdx1 = info.getHomeIdx1();
			homeIdx2 = info.getHomeIdx2();
			locIdx1 = info.getLocIdx1();
			locIdx2 = info.getLocIdx2();
			
			if(!TextUtils.isEmpty(inputEdit3.getText().toString())){
				RequestParams params = new RequestParams();
				params.put("name", inputEdit3.getText().toString());
				if(!TextUtils.isEmpty(inputEdit1.getText().toString())){
					params.put("countryname", inputEdit1.getText().toString());
				}
				HttpClient.getInstance().get2(Constants.API_SEARCH_COLLEGE_URL, params, collegeHandler);
			}
			if(!TextUtils.isEmpty(inputEdit4.getText().toString())){
				RequestParams params = new RequestParams();
				params.put("name", inputEdit4.getText().toString());
				if(!TextUtils.isEmpty(inputEdit1.getText().toString())){
					params.put("countryname", inputEdit1.getText().toString());
				}
				HttpClient.getInstance().get2(Constants.API_SEARCH_COLLEGE_URL, params, collegeHandler2);
			}
		}
	}
	private void registerNow(){
		 int uLocType = 1;
		 String uLocDetail = getLocDetail();
		if (uLocType < 0 || TextUtils.isEmpty(uLocDetail)) {
			Toast.makeText(getApplicationContext(), "所在位置必须选择",
					Toast.LENGTH_SHORT).show();
			return;
		}

		progressDialog = ProgressDialog.show(
				MyLocationInfo2Activity.this, "提示", "正在提交数据...",
				true, false);
		progressDialog.show();

		RequestParams params = new RequestParams();
		params.put("uName", nick);
		params.put("uEmail", username);
		params.put("uPwd", MD5.md5(password));
		params.put("uSign", "暂未编辑签名");
		if (!TextUtils.isEmpty(uPlatform)) {
			params.put("uPlatform", uPlatform);
		}
		if (!TextUtils.isEmpty(uPlatformid)) {
			params.put("uPlatformid", uPlatformid);
		}

		params.put("uGender", gender);

		if (!TextUtils.isEmpty(ShareReferenceUtil
				.getLocationLatitude(getApplicationContext()))) {
			params.put(
					"uGpsX",
					ShareReferenceUtil
							.getLocationLatitude(getApplicationContext()));
		}
		if (!TextUtils.isEmpty(ShareReferenceUtil
				.getLocationLontitude(getApplicationContext()))) {
			params.put(
					"uGpsY",
					ShareReferenceUtil
							.getLocationLontitude(getApplicationContext()));
		}
		Time nowTime = new Time("GMT+8");
		nowTime.setToNow();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(
					"yyyy-MM-dd");
			Date date = sdf.parse(_year + "-" + (_month + 1)
					+ "-" + _day);
			params.put("uBirthday", "" + date.getTime() / 1000);
		} catch (Exception e) {
			e.printStackTrace();
		}
		params.put("uAge", "" + (nowTime.year - _year + 1));
		// params.put("uConstellation", );

		params.put("uLocType", "" + uLocType);
		params.put("uLocDetail", uLocDetail);
		params.put("uSign", signature);
		File photoSavedFile = new File(photoSavedPath);
		if (photoSavedFile != null && photoSavedFile.exists()) {
			try {
				params.put("uIcon", photoSavedFile);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}

		HttpClient.getInstance().post(
				Constants.API_USER_REGISTER_URL, params,
				getHandler());
		
	}
	private String getLocDetail(){
		MyLocationInfo2 info = new MyLocationInfo2();
		info.setType("Returnees");
		info.setCountry(inputEdit1.getText().toString());
		info.setCity(inputEdit2.getText().toString());
		info.setSchool1(inputEdit3.getText().toString());
		info.setSchool2(inputEdit4.getText().toString());
		info.setHome(inputEdit5.getText().toString());
		info.setLoc(inputEdit6.getText().toString());
		info.setCountryIdx(countryIdx);
		info.setCityIdx(cityIdx);
		info.setProvinceIdx(provinceIdx);
		info.setHomeIdx1(homeIdx1);
		info.setHomeIdx2(homeIdx2);
		info.setLocIdx1(locIdx1);
		info.setLocIdx2(locIdx2);
		Gson gson = new Gson();
		return gson.toJson(info);
	}
	
	private void showChooseCountryDialog(String title){
		View inputView = getLayoutInflater().inflate(R.layout.dialog_wheel_1_view, null);
		final WheelView wheel = (WheelView)inputView.findViewById(R.id.wheel_1);
		List<String> countryList = new ArrayList<String>();
		for(CountryData cd:BaseActivity.getCountryList(getApplicationContext())){
			countryList.add(cd.getN());
		}
        wheel.setAdapter(new StringWheelAdapter(countryList));
        wheel.setCurrentItem(countryIdx);
        wheel.setCyclic(true);
        wheel.setInterpolator(new AnticipateOvershootInterpolator());
		AlertDialog.Builder builder = new AlertDialog.Builder(MyLocationInfo2Activity.this);
		builder.setTitle(title);
		builder.setView(inputView);  
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener(){  
			public void onClick(DialogInterface dialog, int whichButton){
				provinceIdx = 0;
				cityIdx = 0;
				inputEdit2.setText("");
				countryIdx = wheel.getCurrentItem();
				inputEdit1.setText(BaseActivity.getCountryList(getApplicationContext()).get(countryIdx).getN());
			}
		});  
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){  
			public void onClick(DialogInterface dialog, int whichButton){}
		}); 
		builder.show();  
	}
	
	private void showChooseCountryDialog2(String title){
		View inputView = getLayoutInflater().inflate(R.layout.dialog_wheel_2_view, null);
		final WheelView wheel1 = (WheelView)inputView.findViewById(R.id.wheel_1);
		final WheelView wheel2 = (WheelView)inputView.findViewById(R.id.wheel_2);
		
		List<String> provinceList = new ArrayList<String>();
		for(ProvinceData cd:BaseActivity.getCountryList(getApplicationContext()).get(countryIdx).getP()){
			provinceList.add(cd.getN());
		}
        wheel1.setAdapter(new StringWheelAdapter(provinceList));
        wheel1.setCurrentItem(provinceIdx);
        wheel1.setCyclic(true);
        wheel1.setInterpolator(new AnticipateOvershootInterpolator());
        wheel1.addChangingListener(new OnWheelChangedListener(){
			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// TODO Auto-generated method stub
				provinceIdx = newValue;
				cityIdx = 0;
				
				List<String> cityList = new ArrayList<String>();
				for(CityData cd:BaseActivity.getCountryList(getApplicationContext()).get(countryIdx).getP().get(provinceIdx).getC()){
					cityList.add(cd.getN());
				}
				wheel2.setAdapter(new StringWheelAdapter(cityList));
				wheel2.setCurrentItem(cityIdx);
			}});
        
		List<String> cityList = new ArrayList<String>();
		for(CityData cd:BaseActivity.getCountryList(getApplicationContext()).get(countryIdx).getP().get(provinceIdx).getC()){
			cityList.add(cd.getN());
		}
        wheel2.setAdapter(new StringWheelAdapter(cityList));
        wheel2.setCurrentItem(cityIdx);
        wheel2.setCyclic(true);
        wheel2.setInterpolator(new AnticipateOvershootInterpolator());
        
		AlertDialog.Builder builder = new AlertDialog.Builder(MyLocationInfo2Activity.this);
		builder.setTitle(title);
		builder.setView(inputView);  
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener(){  
			public void onClick(DialogInterface dialog, int whichButton){
				provinceIdx = wheel1.getCurrentItem();
				cityIdx = wheel2.getCurrentItem();
				if(TextUtils.isEmpty(BaseActivity.getCountryList(getApplicationContext()).get(countryIdx).getP().get(provinceIdx).getN())){
					if(TextUtils.isEmpty(BaseActivity.getCountryList(getApplicationContext()).get(countryIdx).getP().get(provinceIdx).getC().get(cityIdx).getN())){
						inputEdit2.setText(BaseActivity.getCountryList(getApplicationContext()).get(countryIdx).getN());
					}else{
						inputEdit2.setText(BaseActivity.getCountryList(getApplicationContext()).get(countryIdx).getP().get(provinceIdx).getC().get(cityIdx).getN());
					}
				}else{
					inputEdit2.setText(BaseActivity.getCountryList(getApplicationContext()).get(countryIdx).getP().get(provinceIdx).getN()+" "+BaseActivity.getCountryList(getApplicationContext()).get(countryIdx).getP().get(provinceIdx).getC().get(cityIdx).getN());
				}
			}
		});  
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){  
			public void onClick(DialogInterface dialog, int whichButton){}
		}); 
		builder.show();  
	}
	
	private void showChooseCountryDialog3(String title){
		View inputView = getLayoutInflater().inflate(R.layout.dialog_wheel_2_view, null);
		final WheelView wheel1 = (WheelView)inputView.findViewById(R.id.wheel_1);
		final WheelView wheel2 = (WheelView)inputView.findViewById(R.id.wheel_2);
		
		List<String> provinceList = new ArrayList<String>();
		for(ProvinceData cd:BaseActivity.getCountryList(getApplicationContext()).get(0).getP()){
			provinceList.add(cd.getN());
		}
        wheel1.setAdapter(new StringWheelAdapter(provinceList));
        wheel1.setCurrentItem(homeIdx1);
        wheel1.setCyclic(true);
        wheel1.setInterpolator(new AnticipateOvershootInterpolator());
        wheel1.addChangingListener(new OnWheelChangedListener(){
			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// TODO Auto-generated method stub
				homeIdx1 = newValue;
				homeIdx2 = 0;
				List<String> cityList = new ArrayList<String>();
				for(CityData cd:BaseActivity.getCountryList(getApplicationContext()).get(0).getP().get(homeIdx1).getC()){
					cityList.add(cd.getN());
				}
				wheel2.setAdapter(new StringWheelAdapter(cityList));
				wheel2.setCurrentItem(homeIdx2);
			}});
        
		List<String> cityList = new ArrayList<String>();
		for(CityData cd:BaseActivity.getCountryList(getApplicationContext()).get(0).getP().get(homeIdx1).getC()){
			cityList.add(cd.getN());
		}
        wheel2.setAdapter(new StringWheelAdapter(cityList));
        wheel2.setCurrentItem(homeIdx2);
        wheel2.setCyclic(true);
        wheel2.setInterpolator(new AnticipateOvershootInterpolator());
        
		AlertDialog.Builder builder = new AlertDialog.Builder(MyLocationInfo2Activity.this);
		builder.setTitle(title);
		builder.setView(inputView);  
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener(){  
			public void onClick(DialogInterface dialog, int whichButton){
				homeIdx1 = wheel1.getCurrentItem();
				homeIdx2 = wheel2.getCurrentItem();
				if(TextUtils.isEmpty(BaseActivity.getCountryList(getApplicationContext()).get(0).getP().get(homeIdx1).getN())){
					inputEdit5.setText(BaseActivity.getCountryList(getApplicationContext()).get(0).getP().get(homeIdx1).getC().get(homeIdx2).getN());
				}else{
					inputEdit5.setText(BaseActivity.getCountryList(getApplicationContext()).get(0).getP().get(homeIdx1).getN()+" "+BaseActivity.getCountryList(getApplicationContext()).get(0).getP().get(homeIdx1).getC().get(homeIdx2).getN());
				}
			}
		});  
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){  
			public void onClick(DialogInterface dialog, int whichButton){}
		}); 
		builder.show();  
	}
	
	private void showChooseCountryDialog4(String title){
		View inputView = getLayoutInflater().inflate(R.layout.dialog_wheel_2_view, null);
		final WheelView wheel1 = (WheelView)inputView.findViewById(R.id.wheel_1);
		final WheelView wheel2 = (WheelView)inputView.findViewById(R.id.wheel_2);
		
		List<String> provinceList = new ArrayList<String>();
		for(ProvinceData cd:BaseActivity.getCountryList(getApplicationContext()).get(0).getP()){
			provinceList.add(cd.getN());
		}
        wheel1.setAdapter(new StringWheelAdapter(provinceList));
        wheel1.setCurrentItem(locIdx1);
        wheel1.setCyclic(true);
        wheel1.setInterpolator(new AnticipateOvershootInterpolator());
        wheel1.addChangingListener(new OnWheelChangedListener(){
			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// TODO Auto-generated method stub
				locIdx1 = newValue;
				locIdx2 = 0;
				List<String> cityList = new ArrayList<String>();
				for(CityData cd:BaseActivity.getCountryList(getApplicationContext()).get(0).getP().get(locIdx1).getC()){
					cityList.add(cd.getN());
				}
				wheel2.setAdapter(new StringWheelAdapter(cityList));
				wheel2.setCurrentItem(locIdx2);
			}});
        
		List<String> cityList = new ArrayList<String>();
		for(CityData cd:BaseActivity.getCountryList(getApplicationContext()).get(0).getP().get(locIdx1).getC()){
			cityList.add(cd.getN());
		}
        wheel2.setAdapter(new StringWheelAdapter(cityList));
        wheel2.setCurrentItem(locIdx2);
        wheel2.setCyclic(true);
        wheel2.setInterpolator(new AnticipateOvershootInterpolator());
        
		AlertDialog.Builder builder = new AlertDialog.Builder(MyLocationInfo2Activity.this);
		builder.setTitle(title);
		builder.setView(inputView);  
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener(){  
			public void onClick(DialogInterface dialog, int whichButton){
				locIdx1 = wheel1.getCurrentItem();
				locIdx2 = wheel2.getCurrentItem();
				if(TextUtils.isEmpty(BaseActivity.getCountryList(getApplicationContext()).get(0).getP().get(locIdx1).getN())){
					inputEdit6.setText(BaseActivity.getCountryList(getApplicationContext()).get(0).getP().get(locIdx1).getC().get(locIdx2).getN());
				}else{
					inputEdit6.setText(BaseActivity.getCountryList(getApplicationContext()).get(0).getP().get(locIdx1).getN()+" "+BaseActivity.getCountryList(getApplicationContext()).get(0).getP().get(locIdx1).getC().get(locIdx2).getN());
				}
			}
		});  
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){  
			public void onClick(DialogInterface dialog, int whichButton){}
		}); 
		builder.show();  
	}
	private MyResponseHandler getHandler() {
		MyResponseHandler handler = new MyResponseHandler(
				MyLocationInfo2Activity.this, RegisterResponse.class) {
			@Override
			public void onSuccess(String result) {
				super.onSuccess(result);

				if (progressDialog != null) {
					progressDialog.dismiss();
				}
				if (getDataSuccess) {
					RegisterResponse res = (RegisterResponse) response;
					BaseActivity.infoData = res.getData();
					ShareReferenceUtil.saveUserId(getApplicationContext(), res
							.getData().getuId());
					// setAliasAndTags(ShareReferenceUtil.getUserId(getApplicationContext()));
					String infoJson = gson.toJson(res.getData());
					ShareReferenceUtil.saveUserInfoJson(
							getApplicationContext(), infoJson);
					File photoSavedFile = new File(photoSavedPath);
					if (photoSavedFile != null && photoSavedFile.exists()) {
						photoSavedFile.delete();
					}
					// reg push
					RequestParams params = new RequestParams();
					params.put("uId",
							BaseActivity.getMyInfo(getApplicationContext())
									.getuId());
					params.put("uPushIdentifier", ShareReferenceUtil
							.getUserPushId(getApplicationContext()));
					HttpClient.getInstance().get(Constants.API_REG_PUSH_URL,
							params, getHandler2());

					// login huanxin account
					EMChatManager.getInstance().login(infoData.getuId(),
							infoData.getuPwd(), new EMCallBack() {
								@Override
								public void onError(int arg0,
										final String errorMsg) {
									runOnUiThread(new Runnable() {
										public void run() {
											Toast.makeText(
													MyLocationInfo2Activity.this,
													"登录聊天服务器失败，您将收不到消息",
													Toast.LENGTH_SHORT).show();
										}
									});
								}

								@Override
								public void onProgress(int arg0, String arg1) {
								}

								@Override
								public void onSuccess() {
									// 登陆成功，保存用户名密码
									BaseApplication.getInstance().setUserName(
											infoData.getuId());
									BaseApplication.getInstance().setPassword(
											infoData.getuPwd());
									runOnUiThread(new Runnable() {
										public void run() {
											EMGroupManager.getInstance()
													.loadAllGroups();
											EMChatManager.getInstance()
													.loadAllConversations();

										}
									});
									processContactsAndGroups();
									// try {
									// //
									// demo中简单的处理成每次登陆都去获取好友username，开发者自己根据情况而定
									// List<String> usernames =
									// EMChatManager.getInstance().getContactUserNames();
									// System.out.println("-----usernames.size()-----"+usernames.size());
									// Map<String, User> userlist = new
									// HashMap<String, User>();
									// for (String username : usernames) {
									// User user = new User();
									// user.setUsername(username);
									// setUserHearder(username, user);
									// userlist.put(username, user);
									// }
									// // 添加user"新的朋友"
									// User newFriends = new User();
									// newFriends.setUsername(Constant.NEW_FRIENDS_USERNAME);
									// newFriends.setNick("新的朋友");
									// newFriends.setHeader("");
									// userlist.put(Constant.NEW_FRIENDS_USERNAME,newFriends);

									// List<String> userNameList =
									// EMChatDB.getInstance().findAllParticipantsWithMsg();
									// for(String userName:userNameList){
									// User newFriends = new User();
									// newFriends.setUsername(userName);
									// newFriends.setNick("nick"+userName);
									// newFriends.setHeader("");
									// userlist.put(Constant.NEW_FRIENDS_USERNAME,newFriends);
									// }

									// //添加"群聊"
									// // User groupUser = new User();
									// //
									// groupUser.setUsername(Constant.GROUP_USERNAME);
									// // groupUser.setNick("群聊");
									// // groupUser.setHeader("");
									// // userlist.put(Constant.GROUP_USERNAME,
									// groupUser);
									//
									// //存入内存
									// BaseApplication.getInstance().setContactList(userlist);
									// // 存入db
									// UserDao dao = new
									// UserDao(MainActivity.this);
									// List<User> users = new
									// ArrayList<User>(userlist.values());
									// dao.saveContactList(users);
									//
									// // 获取群聊列表,sdk会把群组存入到EMGroupManager和db中
									// EMGroupManager.getInstance().getGroupsFromServer();
									// } catch (Exception e) {
									// e.printStackTrace();
									// }

									// EMChat.getInstance().setAppInited();
								}
							});
					// 登录分享
					UMSocialService mController = UMServiceFactory
							.getUMSocialService("com.umeng.share");
					if (uPlatform != null) {
						if (uPlatform.equals("sina")) {
							mController
									.setShareContent(Constants.LOGIN_SHARE_TEXT);
							mController.setShareMedia(new UMImage(
									getApplicationContext(),
									R.drawable.login_share_image));
							mController.directShare(getApplicationContext(),
									SHARE_MEDIA.SINA, new SnsPostListener() {
										@Override
										public void onStart() {
											// Toast.makeText(getApplicationContext(),
											// "分享开始",Toast.LENGTH_SHORT).show();
										}

										@Override
										public void onComplete(
												SHARE_MEDIA platform,
												int eCode,
												SocializeEntity entity) {
											if (eCode == StatusCode.ST_CODE_SUCCESSED) {
												// Toast.makeText(getApplicationContext(),
												// "分享成功",Toast.LENGTH_SHORT).show();
											} else {
												// Toast.makeText(getApplicationContext(),
												// "分享失败",Toast.LENGTH_SHORT).show();
											}
										}
									});
						}
						// else if(uPlatform.equals("qq")){
						// mController.setShareContent(Constants.LOGIN_SHARE_TEXT);
						// mController.setShareMedia(new
						// UMImage(getApplicationContext(),
						// R.drawable.login_share_image));
						// mController.directShare(getApplicationContext(),
						// SHARE_MEDIA.TENCENT,new SnsPostListener() {
						// @Override
						// public void onStart() {
						// // Toast.makeText(getApplicationContext(),
						// "分享开始",Toast.LENGTH_SHORT).show();
						// }
						//
						// @Override
						// public void onComplete(SHARE_MEDIA platform,int
						// eCode, SocializeEntity entity) {
						// if(eCode == StatusCode.ST_CODE_SUCCESSED){
						// // Toast.makeText(getApplicationContext(),
						// "分享成功",Toast.LENGTH_SHORT).show();
						// }else{
						// // Toast.makeText(getApplicationContext(),
						// "分享失败",Toast.LENGTH_SHORT).show();
						// }
						// }
						// });
						// }else if(uPlatform.equals("weixin")){
						// mController.setShareContent(Constants.LOGIN_SHARE_TEXT);
						// mController.setShareMedia(new
						// UMImage(getApplicationContext(),
						// R.drawable.login_share_image));
						// mController.directShare(getApplicationContext(),
						// SHARE_MEDIA.WEIXIN,new SnsPostListener() {
						// @Override
						// public void onStart() {
						// // Toast.makeText(getApplicationContext(),
						// "分享开始",Toast.LENGTH_SHORT).show();
						// }
						//
						// @Override
						// public void onComplete(SHARE_MEDIA platform,int
						// eCode, SocializeEntity entity) {
						// if(eCode == StatusCode.ST_CODE_SUCCESSED){
						// // Toast.makeText(getApplicationContext(),
						// "分享成功",Toast.LENGTH_SHORT).show();
						// }else{
						// // Toast.makeText(getApplicationContext(),
						// "分享失败",Toast.LENGTH_SHORT).show();
						// }
						// }
						// });
						// }
					}

					startActivity(new Intent(getApplicationContext(),
							MainTabBar.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | 
					                Intent.FLAG_ACTIVITY_CLEAR_TASK |
					                Intent.FLAG_ACTIVITY_NEW_TASK));
					finish();
				}
			}

			@Override
			public void onFailure(Throwable arg0, String result) {
				super.onFailure(arg0, result);

				if (progressDialog != null) {
					progressDialog.dismiss();
				}
				Toast.makeText(getApplicationContext(),
						getString(R.string.network_error_txt),
						Toast.LENGTH_SHORT).show();
			}

		};
		return handler;
	}
	private MyResponseHandler getHandler2(){
		MyResponseHandler handler = new MyResponseHandler(MyLocationInfo2Activity.this,BaseResponse.class){
			@Override
			public void onSuccess(String result) {
				super.onSuccess(result);
				
//				if(getDataSuccess){
//					
//				}
			}
		};
		return handler;
	}
	private void processContactsAndGroups(){
		
		 // 获取群聊列表(群聊里只有groupid和groupname等简单信息，不包含members),sdk会把群组存入到内存和db中
	        try {
				EMGroupManager.getInstance().getGroupsFromServer();
				Map<String, User> userlist = new HashMap<String, User>();
		 
		        // 添加user"申请与通知"
		        User newFriends = new User();
		        newFriends.setUsername(Constant.NEW_FRIENDS_USERNAME);
		        String strChat = "系统消息";
		        newFriends.setNick(strChat);

		        userlist.put(Constant.NEW_FRIENDS_USERNAME, newFriends);
		        
		        BaseApplication.getInstance().setContactList(userlist);
			} catch (EaseMobException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}


	
}
